import { notification } from 'antd';
import { history } from 'umi';

// 运行时配置
export function onRouteChange({ location }: any) {
  const { pathname } = location;

  // 如果不是登录页，检查是否有token
  if (pathname !== '/login') {
    const token = localStorage.getItem('token');
    if (!token) {
      notification.warning({
        message: '请先登录',
        description: '您需要登录后才能访问页面',
      });

      history.push('/login');
    }
  }
}

// 初始化全局状态
export async function getInitialState() {
  // 获取用户信息
  const token = localStorage.getItem('token');
  const userStr = localStorage.getItem('user');

  if (token && userStr) {
    try {
      const user = JSON.parse(userStr);
      return {
        token,
        user,
        isLogin: true,
      };
    } catch (e) {
      return {
        isLogin: false,
      };
    }
  }

  return {
    isLogin: false,
  };
}

// 布局运行时配置
export const layout = () => {
  return {
    // 页面切换时触发
    onPageChange: () => {
      // 获取当前路径
      const pathname = window.location.pathname;

      // 如果不是登录页，检查是否有token
      if (pathname !== '/login') {
        const token = localStorage.getItem('token');
        if (!token) {
          history.push('/login');
        }
      }
    },
    layout: 'mix',
    logout: () => {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      history.push('/login');
    },
  };
};
